package isv

import (
	"dhfshop/models/isv"
	"dhfshop/controllers/base"
	"github.com/astaxie/beego/validation"
	"github.com/astaxie/beego"
	jwt "github.com/dgrijalva/jwt-go"
	"time"
)

type ManagerController struct {
	base.BaseController
}

func (this *ManagerController) Login() {
    v := isv.Manager{}
	this.ParseForm(&v)
	valid := validation.Validation{}
	valid.Required(v.UserName, "user_name")
	valid.Required(v.Password, "password")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return
	}
	manager, err := isv.GetManagerByUsername(v.UserName)	 
	if err != nil {
		this.ServeError("用户信息不存在")
		return 
	}
	v.Salt = manager.Salt            //读取原有的加密盐
	v.PasswordHashed = isv.EncryptPassword(manager.Salt, v.Password)
	if v.PasswordHashed != manager.PasswordHashed {
		this.ServeError("密码错误")
		return
	}
	token := jwt.New(jwt.GetSigningMethod("HS256"))
	claims := token.Claims.(jwt.MapClaims)
	claims["CurrentUser"] = struct {
	    Id int64
		CompanyId int
		Role int
	}{Id: manager.ManagerId, CompanyId: int(manager.ManagerId), Role: 4}
	claims["exp"] = time.Now().UTC().Add(time.Hour * 24 * 1).Unix()
	tokenSecret := beego.AppConfig.String("AuthTokenSecret")
	tokenString, err := token.SignedString([]byte(tokenSecret))
	if err != nil {
		this.ServeError("登录失败，请稍后再试")
		return
	}
	this.Data["json"] = map[string]string{
	    "token": tokenString,
	}
	this.ServeJSON()
}

func (this *ManagerController) SetUserPassword() {
    v := struct {
	    UserId        int64     `form:"-" valid:"Required"`
	    OldPassword   string  `form:"old_passwd" valid:"Required"`
	    NewPassword   string  `form:"new_passwd" valid:"Required"`
	}{}
	this.ParseForm(&v)
	v.UserId = int64(this.Ctx.Input.GetData("curUserId").(int))
	valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
	    this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return
	}
    manager, err := isv.GetManagerById(int64(v.UserId))
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	manager.Password = v.OldPassword
	curLoginPwdHashed := isv.EncryptPassword(manager.Salt, v.OldPassword)   //需要提前给这两个参数赋值 Salt、Password	
	if curLoginPwdHashed != manager.PasswordHashed {
		this.ServeError("old_passwd is error")
		return
	}
	manager.Password = v.NewPassword
	if err := isv.UpdateManagerPasswd(manager); err != nil {
	    this.ServeError(err.Error())
		return
	}
	this.ServeOk("update password success")
}
